package com.czl.module_service.view

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View


/**
 * @author by xubin,
 * @date on 2022/1/18.
 * PS: Not easy to write code, please indicate.
 */
class SpringProgressView(context: Context?, attrs: AttributeSet?) : View(context, attrs) {

    /**
     * 分段颜色
     */
    private val SECTION_COLORS = intArrayOf(Color.RED, Color.parseColor("#ffa000"), Color.YELLOW)

    /**
     * 进度条最大值
     */
    private var maxCount = 0f

    /**
     * 进度条当前值
     */
    private var currentCount = 0f

    /**
     * 画笔
     */
    private val mPaint by lazy {
        Paint().also {
            it.color = Color.GRAY
            it.style = Paint.Style.FILL
        }
    }
    private var mWidth = 0
    private var mHeight: Int = 0

    private val rectBg = RectF()
    private val rectProgressBg = RectF()
    private var shader: LinearGradient? = null

    override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) {
        super.onLayout(changed, left, top, right, bottom)
        mHeight = bottom - top
        mWidth = right - left
        rectBg[0f, 0f, mWidth.toFloat()] = mHeight.toFloat()
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        val section = currentCount / maxCount
        if (shader == null) {
            shader =
                LinearGradient(0f, 0f, mWidth.toFloat(), mHeight.toFloat(), 0, 0, Shader.TileMode.CLAMP)
        }
        mPaint.shader = shader
        mPaint.isAntiAlias = true
        mPaint.style = Paint.Style.STROKE

        //绘制进度条外側边框
        val round: Float = (mHeight * 2 / 3).toFloat()
        canvas.drawRoundRect(rectBg, round, round, mPaint)

        //绘制进度条
        mPaint.style = Paint.Style.FILL
        val pl = (mWidth * (1 - section)).toInt()
        rectProgressBg[pl.toFloat(), 0f, mWidth.toFloat()] = mHeight.toFloat()
        canvas.drawRoundRect(rectProgressBg, round, round, mPaint)
    }

    /*
     * 设置最大的进度值
     */
    fun setMaxCount(maxCount: Float) {
        this.maxCount = maxCount
    }

    /**
     * 设置当前的进度值
     */
    fun setCurrentCount(currentCount: Float) {
        this.currentCount = if (currentCount > maxCount) maxCount else currentCount
        invalidate()
    }

    fun getMaxCount(): Float {
        return maxCount
    }

    fun getCurrentCount(): Float {
        return currentCount
    }
}